package com.example.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginIntercepter implements HandlerInterceptor {

    @Autowired
    RedisTemplate redisTemplate;

//    请求之前拦截
    @Override
    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {

        String token = request.getHeader("token");
        if(token==null||token.isEmpty()){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }

        Object obj = redisTemplate.opsForValue().get(token);
        if(obj==null){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }else {
            return true;
        }
    }
}
